<?
include_once("/home/gru/public_html_dev/lib/fb.php");
function _($v){
	//fb($v);
}

//크론정지
//exit;

function cropImg($imgURL,$w,$h,$f_er,$name){

	$today = date("Ymd");
	$dir = '/home/gru/img/'.$f_er.'/'.$today.'/';
	$file= '/home/gru/img/'.$f_er.'/'.$name;
	
	if(!file_exists($dir)){
		if(!mkdir($dir)){
			echo "error mkdir get.php";
			return 0;
		}
	}
  
  	if($imgURL=="")return;	
	if(is_file($file))return;
	
	try{		
	  $im = new Imagick();
	  $im->readImage($imgURL);
	  $im->cropThumbnailImage ( $w, $h );
	  
	  $im->writeImage($file);
	  $im->destroy();
	}catch(Exception $e){
		echo $e->getMessage();
	}
}


function getAreaCode($area1,$shop_addr){
		
// 지역코드 추출하는 새로운 로직, 필요한 것은 $area1과 $shop_adr      	
$code01 = ""; $code02 = ""; 
$code1  = ""; $code2  = "";

$shop_addr = str_replace("특별시", "", $shop_addr);
$shop_addr = str_replace("광역시", "", $shop_addr);
$shop_addr = str_replace("특별자치도", "", $shop_addr);
$shop_addr = str_replace("서울시",   "서울 ", $shop_addr); $shop_addr = str_replace("서울", "서울 ", $shop_addr);
$shop_addr = str_replace("인천시",   "인천 ", $shop_addr); $shop_addr = str_replace("인천", "인천 ", $shop_addr);
$shop_addr = str_replace("대전시",   "대전 ", $shop_addr); $shop_addr = str_replace("대전", "대전 ", $shop_addr);
$shop_addr = str_replace("대구시",   "대구 ", $shop_addr); $shop_addr = str_replace("대구", "대구 ", $shop_addr);
$shop_addr = str_replace("부산시",   "부산 ", $shop_addr); $shop_addr = str_replace("부산", "부산 ", $shop_addr);
$shop_addr = str_replace("광주시",   "광주 ", $shop_addr); $shop_addr = str_replace("광주", "광주 ", $shop_addr);
$shop_addr = str_replace("울산시",   "울산 ", $shop_addr); $shop_addr = str_replace("울산", "울산 ", $shop_addr);
$shop_addr = str_replace("경기도",   "경기 ", $shop_addr); $shop_addr = str_replace("경기", "경기 ", $shop_addr);
$shop_addr = str_replace("강원도",   "강원 ", $shop_addr); $shop_addr = str_replace("강원", "강원 ", $shop_addr);
$shop_addr = str_replace("제주도",   "제주 ", $shop_addr); $shop_addr = str_replace("제주", "제주 ", $shop_addr); 
$shop_addr = str_replace("제주 시", "제주시 ", $shop_addr);
$shop_addr = str_replace("경상북도", "경북 ", $shop_addr); $shop_addr = str_replace("경북", "경북 ", $shop_addr);
$shop_addr = str_replace("경상남도", "경남 ", $shop_addr); $shop_addr = str_replace("경남", "경남 ", $shop_addr);
$shop_addr = str_replace("충청북도", "충북 ", $shop_addr); $shop_addr = str_replace("충북", "충북 ", $shop_addr);
$shop_addr = str_replace("충청남도", "충남 ", $shop_addr); $shop_addr = str_replace("충남", "충남 ", $shop_addr);
$shop_addr = str_replace("전라북도", "전북 ", $shop_addr); $shop_addr = str_replace("전북", "전북 ", $shop_addr);
$shop_addr = str_replace("전라남도", "전남 ", $shop_addr); $shop_addr = str_replace("전남", "전남 ", $shop_addr);
$shop_addr = str_replace("  ", " ", $shop_addr); $shop_addr = str_replace("  ", " ", $shop_addr);

$addr      = explode(" ", $shop_addr); _($addr); echo "<br>";

$nation   = array("전국", "기타");
$province = array("경기", "강원", "제주", "경북", "경남", "충북", "충남", "전북", "전남");
$bigcity  = array("서울", "인천", "대전", "대구", "부산", "광주", "울산");
$addcity  = array("고양", "부천", "성남", "수원", "안산", "안양", "용인", "창원", "포항", "전주", "천안", "청주", "고양시", "부천시", "성남시", "수원시", "안산시", "안양시", "용인시", "창원시", "포항시", "전주시", "천안시", "청주시");

        
// 전국, 기타, 배송 등
if (in_array($area1, $nation) || mb_strpos("찾기".$shop_addr, "전국", 0, "utf-8") || mb_strpos("찾기".$shop_addr, "배송", 0, "utf-8")){
	//A0 	전국 	A0 		17 	A99 	B00 	전국
	$code01 = "A99"; $code02 = "B00";
	$code1  = "A0";  $code2  = "";
	echo "code1: $code01 || code2: $code02<br>";
}
else
{
    if (!$area1 && !$shop_addr){//지역 주소 모두 없다면 전국
		$code01 = "A99"; $code02 = "B00";
		$code1  = "A0";  $code2  = "";
	}
	else if ($area1 && $shop_addr)//지역 주소가 있다면
    {
    	if ((in_array($addr[0], $province) || in_array($addr[0], $bigcity)) && ($area1 != $addr[0]))  // 1depth가 안맞을 때는 주소를 기준으로 강제 변경
    	{
			echo "Reset area1: $area1 --> ${addr[0]}<br>";
    		$area1 = $addr[0];
		}
		 
    	if ($area1 == "제주") $shop_addr = trim(str_replace("제주 ", "", $shop_addr));
		else $shop_addr = trim(str_replace($area1." ", "", $shop_addr));

		$addr      = explode(" ", $shop_addr); _($addr); echo "<br>";
		
        $query01  = "SELECT * FROM _area_code WHERE NAME01='$area1' GROUP BY NAME01";
        $result01 = mysql_query($query01);
        //echo "${query01}<br>";
        $num_result01 = mysql_num_rows($result01);
        
        if ($num_result01)
        {
            $record01 = mysql_fetch_array($result01);
            $code01 = $record01[CODE01]; $code1 = $record01[CODE1]; echo "code01: $code01<br>";
            
            $query02  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[0]}%' OR NAME02 LIKE '%${addr[0]}%')";
            $result02 = mysql_query($query02);
            //echo "${query02}<br>";
            $num_result02 = mysql_num_rows($result02);
            
            if ($num_result02 == 1)
            {
                $record02 = mysql_fetch_array($result02);
                $code02 = $record02[CODE02]; $code2 = $record02[CODE2]; echo "code02: $code02<br>";
            }
            else if ($num_result02 > 1)  // a) 3depth가 필요하거나, b) 대구 서구/달서구 같은 경우
            {
                while ($record02 = mysql_fetch_array($result02))  // b)를 먼저 처리하고
                {
                    if ($addr[0] == $record02[NAME2] || $addr[0] == $record02[NAME02])
                    {
                        $code02 = $record02[CODE02]; $code2 = $record02[CODE2]; echo "code02: $code02<br>";
                    }
                }
            
                if (!$code02)  // a)를 처리, 3depth를 찾는다
                {
                    $query03  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[1]}%' OR NAME02 LIKE '%${addr[1]}%')";
                    $result03 = mysql_query($query03);
                    //echo "${query03}<br>";
                    $num_result03 = mysql_num_rows($result03);
                    
                    if ($num_result03 == 1)
                    {
                        $record03 = mysql_fetch_array($result03);
                        $code02 = $record03[CODE02]; $code2 = $record03[CODE2]; echo "code02: $code02<br>";
                    }
                    else echo "could not found code02<br>";
                }
            }
            else if ($num_result02 == 0)  // 대부분 띄워쓰기가 안되어 있는 경우
            {
                $addr_len = mb_strlen($addr[0], "utf-8"); echo "addr[0]: ${addr[0]} (${addr_len})<br>";
                
                if ($addr_len > 4)
                {
                    if (in_array($area1, $bigcity))
                    {
                        $temp = mb_substr($addr[0], 0, 3, "utf-8");
                        if ($temp == "구로구") $addr[0] = $temp;
                        else { $addr = explode("구", $addr[0]); $addr[0] .= "구"; }
                    }
                    else
					{
						echo "3rd char: ".mb_substr($addr[0], 2, 1, "utf-8")."<br>";
						if (mb_substr($addr[0], 2, 1, "utf-8") == "군") { $addr = explode("군", $addr[0]); $addr[0] .= "군"; }
						else { $addr = explode("시", $addr[0]); $addr[0] .= "시"; }
					}
                    
                    if (in_array($addr[0], $addcity)) { $addr = explode("구", $addr[1]); $addr[0] .= "구"; }
                    
                    _($addr); echo "<br>";

                    $query04  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[0]}%' OR NAME02 LIKE '%${addr[0]}%')";
                    $result04 = mysql_query($query04);
                    echo "${query04}<br>";
                    $num_result04 = mysql_num_rows($result04);
                    
                    if ($num_result04 == 1)
                    {
                        $record04 = mysql_fetch_array($result04);
                        $code02 = $record04[CODE02]; $code2 = $record04[CODE2]; echo "code02: $code02<br>";
                    }
                    else if ($num_result04 > 1) // 3a) depth가 필요하거나, b) 대구서구/대구달서구 같은 경우
                    {
                        
                        while ($record04 = mysql_fetch_array($result04)) // b)를 먼저 처리하고
                        {
                            if ($addr[0] == $record04[NAME2] || $addr[0] == $record04[NAME02])
                            {
                                $code02 = $record04[CODE02]; $code2 = $record04[CODE2]; echo "code02: $code02<br>";
                            }
                        }
                    
                        if (!$code02) // a)를 처리, 3depth를 찾는다
                        {
                            $query05  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[1]}%' OR NAME02 LIKE '%${addr[1]}%')";
                            $result05 = mysql_query($query05);
                            echo "${query05}<br>";
                            $num_result05 = mysql_num_rows($result05);
                            
                            if ($num_result05 == 1)
                            {
                                $record05 = mysql_fetch_array($result05);
                                $code02 = $record05[CODE02]; $code2 = $record05[CODE2]; echo "code02: $code02<br>";
                            }
                            else echo "could not found code02<br>";
                        }
                    }

                }
                else
				{
		            $query06  = "SELECT * FROM _area_code WHERE NAME1 LIKE '%${addr[0]}%' OR NAME01 LIKE '%${addr[0]}%' GROUP BY NAME01";
		            $result06 = mysql_query($query06);
		            echo "${query06}<br>";
		            $num_result06 = mysql_num_rows($result06);
		
		            $query07  = "SELECT * FROM _area_code WHERE NAME2 LIKE '%${addr[0]}%' OR NAME02 LIKE '%${addr[0]}%' GROUP BY NAME02";
		            $result07 = mysql_query($query07);
		            echo "${query07}<br>";
		            $num_result07 = mysql_num_rows($result07);

		            if ($num_result06)
		            {
		                $record06 = mysql_fetch_array($result06);
		                $code01 = $record06[CODE01]; $code1 = $record06[CODE1]; echo "code01: $code01<br>";
	
		                $query08  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[1]}%' OR NAME02 LIKE '%${addr[1]}%')";
		                $result08 = mysql_query($query08);
		                echo "${query08}<br>";
		                $num_result08 = mysql_num_rows($result08);
		                
		                if ($num_result08 == 1)
		                {
		                    $record08 = mysql_fetch_array($result08);
		                    $code02 = $record08[CODE02]; $code2 = $record08[CODE2]; echo "code02: $code02 [ ${record08[NAME2]} ]<br>";
		                }
		                else echo "could not found code02<br>";
		            }
		
		            if ($num_result07)
		            {
		                $record07 = mysql_fetch_array($result07);
		                $code01 = $record07[CODE01]; $code1 = $record07[CODE1]; echo "Reset code01: $code01 [ ${record07[NAME01]} ]<br>";
						
						if ($num_result07 == 1)
						{
			                $code02 = $record07[CODE02]; $code2 = $record07[CODE2]; echo "code02: $code02 [ ${addr[0]} ]<br>";
						}
						else
						{
			                $query08  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[1]}%' OR NAME02 LIKE '%${addr[1]}%')";
			                $result08 = mysql_query($query08);
			                echo "${query08}<br>";
			                $num_result08 = mysql_num_rows($result08);
			                
			                if ($num_result08 == 1)
			                {
			                    $record08 = mysql_fetch_array($result08);
			                    $code02 = $record08[CODE02]; $code2 = $record08[CODE2]; echo "code02: $code02 [ ${record08[NAME2]} ]<br>";
			                }
			                else if ($num_result08 > 1)  // a) 3depth가 필요하거나, b) 대구 서구/달서구 같은 경우
			                {
			                    while ($record08 = mysql_fetch_array($result08))  // b)를 먼저 처리하고
			                    {
			                        if ($addr[0] == $record08[NAME2] || $addr[0] == $record08[NAME02])
			                        {
			                            $code02 = $record08[CODE02]; $code2 = $record08[CODE2]; echo "code02: $code02<br>";
			                        }
			                    }
			                
			                    if (!$code02)  // a)를 처리, 3depth를 찾는다
			                    {
			                        $query03  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[2]}%' OR NAME02 LIKE '%${addr[2]}%')";
			                        $result03 = mysql_query($query03);
			                        echo "${query03}<br>";
			                        $num_result03 = mysql_num_rows($result03);
			                        
			                        if ($num_result03 == 1)
			                        {
			                            $record03 = mysql_fetch_array($result03);
			                            $code02 = $record03[CODE02]; $code2 = $record03[CODE2]; echo "code02: $code02<br>";
			                        }
			                        else echo "could not found code02<br>";
			                    }
			                }

			                else echo "could not found code02<br>";
		                }			
		            }
				}
            }
        }
		else echo "area1 is not correct<br>";
    }
    else if (!$area1 && $shop_addr) 
    {
        $query06  = "SELECT * FROM _area_code WHERE NAME1 LIKE '%${addr[0]}%' OR NAME01 LIKE '%${addr[0]}%' GROUP BY NAME01";
        $result06 = mysql_query($query06);
        echo "${query06}<br>";
        $num_result06 = mysql_num_rows($result06);

        $query07  = "SELECT * FROM _area_code WHERE NAME2 LIKE '%${addr[0]}%' OR NAME02 LIKE '%${addr[0]}%' GROUP BY NAME02";
        $result07 = mysql_query($query07);
        echo "${query07}<br>";
        $num_result07 = mysql_num_rows($result07);

        if ($num_result06)
        {
            $record06 = mysql_fetch_array($result06);
            $code01 = $record06[CODE01]; $code1 = $record06[CODE1]; echo "code01: $code01<br>";

            $query08  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[1]}%' OR NAME02 LIKE '%${addr[1]}%')";
            $result08 = mysql_query($query08);
            echo "${query08}<br>";
            $num_result08 = mysql_num_rows($result08);
            
            if ($num_result08 == 1)
            {
                $record08 = mysql_fetch_array($result08);
                $code02 = $record08[CODE02]; $code2 = $record08[CODE2]; echo "code02: $code02 [ ${record08[NAME2]} ]<br>";
            }
			else if ($num_result08 > 1)
			{
                $query09  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[2]}%' OR NAME02 LIKE '%${addr[2]}%')";
                $result09 = mysql_query($query09);
                echo "${query09}<br>";
                $num_result09 = mysql_num_rows($result09);
                
                if ($num_result09 == 1)
                {
                    $record09 = mysql_fetch_array($result09);
                    $code02 = $record09[CODE02]; $code2 = $record09[CODE2]; echo "code02: $code02 [ ${record09[NAME2]} ]<br>";
                }
            else echo "could not found code02<br>";
            }
        }

        if ($num_result07)
        {
            $record07 = mysql_fetch_array($result07);
            $code01 = $record07[CODE01]; $code1 = $record07[CODE1]; echo "code01: $code01 [ ${record07[NAME01]} ]<br>";
			
			if ($num_result07 == 1)
			{
                $code02 = $record07[CODE02]; $code2 = $record07[CODE2]; echo "code02: $code02 [ ${addr[0]} ]<br>";
			}
			else if ($num_result07 > 1)
			{
                $query08  = "SELECT * FROM _area_code WHERE CODE01='$code01' AND (NAME2 LIKE '%${addr[1]}%' OR NAME02 LIKE '%${addr[1]}%')";
                $result08 = mysql_query($query08);
                echo "${query08}<br>";
                $num_result08 = mysql_num_rows($result08);
                
                if ($num_result08 == 1)
                {
                    $record08 = mysql_fetch_array($result08);
                    $code02 = $record08[CODE02]; $code2 = $record08[CODE2]; echo "code02: $code02 [ ${record08[NAME2]} ]<br>";
                }
                else echo "could not found code02<br>";
            }			
        }

    }
}

if (!$code01)                 { echo "code01 not found: skipped<br>"; } 
else if ($code01 && !$code02) { echo "code01 found, code02 not found: code02 set to [공통]<br>"; $code02="B99"; } // 안찾아지면 일단 공통 처리
else if ($code01 && $code02)  { echo "code01 and code02 found<br>"; }                    
     
	 $arr = array($code1,$code2,$code01,$code02);
	 return $arr;
}



$connect = mysql_connect("localhost","root","qhdksdusrntlf", true) or die( "error DB connection");
mysql_select_db('gru', $connect);
mysql_query("set names utf8");


$start = microtime();
$str = explode(" ",$start);
$start = $str[0]+$str[1];
echo $start."<br>";

//-----------------------------------------------------------------------------
// 전체생성처리
//-----------------------------------------------------------------------------

$nation   = array("전국", "기타");
$province = array("경기", "강원", "제주", "경북", "경남", "충북", "충남", "전북", "전남");
$bigcity  = array("서울", "인천", "대전", "대구", "부산", "광주", "울산");
$addcity  = array("고양", "부천", "성남", "수원", "안산", "안양", "용인", "창원", "포항", "전주", "천안", "청주", "고양시", "부천시", "성남시", "수원시", "안산시", "안양시", "용인시", "창원시", "포항시", "전주시", "천안시", "청주시");

// 지정된 상품분류정보 추출 ///////////////////////////////////////////////
$i = 0;
$query31  = "SELECT * FROM _good_code WHERE m5_code != ''";
$result31 = mysql_query($query31);
while ($record31 = mysql_fetch_array($result31))
{
	$gname[$i] = $record31[m5_gname];
	$bkbn[$i]  = $record31[m5_bkbn];
	$code[$i]  = $record31[m5_code];
	$i++;
}
$num_bkbn = count($bkbn);


//rss신청업체 정보 추출
$Query  = " SELECT * FROM _meta_site WHERE kbn = 'Y'";

$Result = mysql_query($Query);
$RecCnt = mysql_num_rows($Result);
$Cnt = 0;


echo $RecCnt;
//_meta_site루프돌면서 데이터 수집
while ($Record = mysql_fetch_array($Result))
{
	
	$rss_addr = $Record[link];// rss경로
	$domain   = $Record[domain];// 도메인
	$mId    = $Record[id];
	

	//echo "<hr>".$mId."[ ".$domain." ] - ".$rss_addr." <BR><hr>";
	
	$xml = @simplexml_load_file($rss_addr);// 해당 rss정보를 읽어들인다
	if($xml == NULL)continue;

	if (eregi("couponmoa", $rss_addr)){//쿠폰모아형태
		$for_count = $xml->deals->deal;
	}
	else if (eregi("socialxml", $rss_addr)){
		$for_count = $xml->item;
	}
	else if (eregi("wemakeprice_basic.xml", $rss_addr)){
		$for_count = $xml->product;
	}
	else{
		$for_count = $xml->product;
	}
	
	//전처리 : 상품부류 정보 프리로딩
	$i = 0;
	$query31  = "SELECT * FROM _good_code WHERE m5_code != ''";
	$result31 = mysql_query($query31);
	while ($record31 = mysql_fetch_array($result31))
	{
		$gname[$i] = $record31[m5_gname];
		$bkbn[$i]  = $record31[m5_bkbn];
		$code[$i]  = $record31[m5_code];
		$i++;
	}
	$num_bkbn = count($bkbn);
	
	
	//상품 갯수 입력
	$uDate = date("Ymd")."_".$domain;
	$itemCnt = count($for_count);
	$sql = "insert into coupon_cnt  set link='$rss_addr',cnt=$itemCnt,mid =$mId, domain ='$domain',uDate='$uDate'
ON DUPLICATE KEY UPDATE link='$rss_addr',cnt=$itemCnt,mid =$mId, domain ='$domain'";
	mysql_query($sql);
	
	
	// 상품정보추출(다수가 있을수 있음 지역별상품)
	for ($i = 0; $i < $itemCnt; $i++)
	{
		$pid           = "";
		$url           = "";
		$area1         = "";
		$area2         = "";
		$category      = "";
		$name          = "";
		$mimg          = "";
		$caution       = "";
		$desc          = "";
		$detail        = "";
		$price         = "";
		$saleprice     = "";
		$salerate      = "";
		$mincnt        = "";
		$maxcnt        = "";
		$salecnt       = "";
		$startdate     = "";
		$enddate       = "";
		$shop_location = "";
		$shop_name     = "";
		$shop_addr     = "";

		//-----------------------------------------------------------------
		// xml종류에 따른 처리
		//-----------------------------------------------------------------
		if (eregi("couponmoa", $rss_addr))                                      // couponmoa xml 처리
		{
			echo "xml type: couponmoa<br>";
			$pid           = $xml->deals->deal[$i]->meta_id;                        // 상품코드
			$url           = $xml->deals->deal[$i]->url;                            // 상품링크
			$category      = $xml->deals->deal[$i]->category;                       // 카테고리명
			$name          = $xml->deals->deal[$i]->title;                          // 상품명
			$mimg          = $xml->deals->deal[$i]->images->image;                  // 상품이미지
			$caution       = $xml->deals->deal[$i]->description;                    // 사용안내(주의사항)
			$desc          = $xml->deals->deal[$i]->description;                    // sms구문
			$price         = $xml->deals->deal[$i]->original;                       // 판매가
			$saleprice     = $xml->deals->deal[$i]->price;                          // 할인가
			$salerate      = $xml->deals->deal[$i]->discount;                       // 할인율
			$mincnt        = $xml->deals->deal[$i]->min_count;                      // 최소구매도달인원 
			$maxcnt        = $xml->deals->deal[$i]->max_count;                      // 최대수량
			$salecnt       = $xml->deals->deal[$i]->now_count;                      // 현재판매량
			$startdate     = $xml->deals->deal[$i]->start_at;                       // 판매시작일
			$enddate       = $xml->deals->deal[$i]->end_at;                         // 판매종료일
			$shop_location = $xml->deals->deal[$i]->shops->shop->shop_address;      // 매장위치
			$shop_name     = $xml->deals->deal[$i]->shops->shop->shop_name;         // 공급업체명
			$shop_addr     = $xml->deals->deal[$i]->shops->shop->shop_address;      // 공급업체주소
			$ckbn = "couponmoa";
		}
		else if (eregi("socialxml", $rss_addr))
		{
			echo "xml type: socialxml<br>";
			$url           = $xml->item[$i]->link;                                  // 상품링크
			$area1         = $xml->item[$i]->area;                                  // 지역
			$category      = $xml->item[$i]->category;                              // 카테고리명
			$name          = $xml->item[$i]->title;                                 // 상품명
			$mimg          = $xml->item[$i]->photo1;                                // 상품이미지
			$desc          = $xml->item[$i]->desc_text;                             // sms구문
			$price         = $xml->item[$i]->price_original;                        // 판매가
			$saleprice     = $xml->item[$i]->price_now;                             // 할인가
			$salerate      = $xml->item[$i]->sale_percent;                          // 할인율
			$mincnt        = $xml->item[$i]->count_min;                             // 최소구매도달인원 
			$maxcnt        = $xml->item[$i]->count_max;                             // 최대수량
			$salecnt       = $xml->item[$i]->sell_count;                            // 현재판매량
			$startdate     = $xml->item[$i]->time_start;                            // 판매시작일
			$enddate       = $xml->item[$i]->time_end;                              // 판매종료일
			$shop_name     = $xml->item[$i]->shop;                                  // 공급업체명
			$shop_addr     = $xml->item[$i]->addr;                                  // 공급업체주소

			// 상품코드 추출 //////////////////////////////////////////////////
			$tmp = explode("?", $url); // _($tmp); echo "<br>";

			if      (eregi("wemakeprice",     $tmp[0])) { $tmp2 = explode("/", $tmp[0]); $pid = $tmp2[count($tmp2)-2]; _($tmp2); echo "[${pid}]<br>";                          } // wemakeprice용  ex) http://www.wemakeprice.com/deal/adeal/26756/?utm_source=couponmoa&utm_medium=metasite&utm_campaign=metasitelist&src=text&kw=0019EA
			else if (eregi("groupon",         $tmp[0])) { $tmp2 = explode("/", $tmp[0]); $pid = $tmp2[count($tmp2)-1]; _($tmp2); echo "[${pid}]<br>";                           } // groupon용  ex) http://www.groupon.kr/app/Product/pview/21798?CID=KR_AFF_1_129&CPS=KR_AFF_1_129&utm_source=AFF_1&utm_medium=129
			else if (eregi("copon",           $tmp[0])) { $tmp2 = explode("/", $tmp[0]); $pid = $tmp2[count($tmp2)-1]; _($tmp2); echo "[${pid}]<br>";                           } // copon용  ex) http://www.copon.co.kr/430?meta_ref=meta_do
			else if (eregi("p_no=",           $tmp[1])) { $tmp2 = explode("p_no=", $tmp[1]); $pid = $tmp2[1];						} // 티몬 등 ex) http://www.ticketmonster.co.kr/entry/?jp=80003&ln=7693&p_no=2894909
			else if (eregi("coupang=",        $tmp[1])) { $tmp2 = explode("coupang=", $tmp[1]); $pid = $tmp2[1];                    }
			else if (eregi("dailystrip",      $tmp[0])) { $tmp2 = explode("&", $tmp[1]); $pid = str_replace("com_id=", "", $tmp2[0]);  } // com_id 뒤 알파벳 세자리가 pid ex) http://www.dailystrip.co.kr/main/today.asp?com_id=QCN&img_num=6&dates=20120518
			else if (eregi("wipon_key",       $tmp[1])) { $tmp2 = explode("wipon_key=", $tmp[1]); $pid = $tmp2[1];                  }
			else if (eregi("couponism.net",   $tmp[0])) { $tmp2 = explode("/", $tmp[0]); $pid = $tmp2[3];                           }
			else if (eregi("twt.pn",          $tmp[0])) { $tmp2 = explode("/", $tmp[0]); $pid = $tmp2[3];                           }
			else if (eregi("blackfridays.cc", $tmp[0])) { $tmp2 = explode("/", $tmp[0]); $pid = $tmp2[3];                           }
			else if (eregi("obbacha.com",     $tmp[0])) { $tmp2 = explode("/", $tmp[0]); $pid = $tmp2[3];                           }
			else if (eregi("ishoppang.com",   $tmp[0])) { $pid = str_replace("si=g_", "", $tmp[1]);                                  }
			else if (eregi("dalincoupon.com", $tmp[0])) { $tmp2 = explode("Pid=", $tmp[1]); $pid = $tmp2[1];                        }
			else if (eregi("smallmonkey.co.kr",$tmp[0])){ $tmp2 = explode("/", $tmp[0]); $pid = $tmp2[5];                           }
			else if (eregi("product_number=", $tmp[1])) { $tmp2 = explode("product_number=", $tmp[1]); $pid = $tmp2[1];             }
			else if (eregi("product_no=",     $tmp[1])) { $pid = str_replace("product_no=", "", $tmp[1]);                           }
			else if (eregi("viewCode=",       $tmp[1])) { $tmp2 = explode("viewCode=", $tmp[1]); $pid = substr($tmp2[1], 0, 8);     }
			else if (eregi("main=today",      $tmp[1])) { $pid = substr($tmp[0], -7, -1);                                           }
			else if (eregi("goods_id=",       $tmp[1])) { $pid = str_replace("goods_id=", "", $tmp[1]);                             }
			else if (eregi("p_code=",         $tmp[1])) { $pid = str_replace("p_code=", "", $tmp[1]);                               }
			else if (eregi("code=",           $tmp[1])) { $pid = str_replace("code=", "", $tmp[1]);                                 }
			else if (eregi("pd_idx=",         $tmp[1])) { $tmp2 = explode("pd_idx=", $tmp[1]); $pid = $tmp2[1];                     }
			else if (eregi("tgIdx=",          $tmp[1])) { $tmp2 = explode("tgIdx=", $tmp[1]); $pid = $tmp2[1];                      }
			else if (eregi("gidx=",           $tmp[1])) { $tmp2 = explode("gidx=", $tmp[1]); $pid = $tmp2[1];                       }
			else if (eregi("pidx=",           $tmp[1])) { $tmp2 = explode("&", $tmp[1]); $pid = str_replace("pidx=", "", $tmp2[0]); }
			else if (eregi("id_str=",         $tmp[1])) { $tmp2 = explode("&", $tmp[1]); $pid = str_replace("id_str=", "", $tmp2[0]); }
			else if (eregi("pID=",            $tmp[1])) { $tmp2 = explode("&", $tmp[1]); $pid = str_replace("pID=", "", $tmp2[0]);  }
			else if (eregi("no=",             $tmp[1])) { $pid = str_replace("no=", "", $tmp[1]);                                   }
			else if (eregi("id=",             $tmp[1])) { $pid = str_replace("id=", "", $tmp[1]);                                   }
			else if (eregi("seq=",            $tmp[1])) { $pid = str_replace("seq=", "", $tmp[1]);                                  }
			else if (eregi("prd=",            $tmp[1])) { $tmp2 = explode("prd=", $tmp[1]); $pid = $tmp2[1];                        }
			$ckbn = "socialxml";
		}
		else                                            // 원데이넷 xml 처리
		{
			echo "xml type: onedaynet<br>";
			if ($xml->product[$i]->limitdate)
			{
				$pid           = $xml->product[$i]->pid;                                // 상품코드
				$url           = $xml->product[$i]->url;                                // 상품링크
				$area1         = $xml->product[$i]->region;                             // 지역1
				$area2         = "";                                                    // 지역2
				$category      = "";                                                    // 카테고리명
				$name          = $xml->product[$i]->name;                               // 상품명
				$mimg          = $xml->product[$i]->image1;                             // 상품이미지
				$caution       = $xml->product[$i]->descript;                           // 사용안내(주의사항)
				$desc          = $xml->product[$i]->descript;                           // sms구문
				$detail        = "";                                                    // 상품상세설명
				$price         = $xml->product[$i]->price;                              // 판매가
				$saleprice     = $xml->product[$i]->saleprice;                          // 할인가
				$salerate      = $xml->product[$i]->salerate;                           // 할인율
				$mincnt        = $xml->product[$i]->mincnt;                             // 최소구매도달인원 
				$maxcnt        = $xml->product[$i]->maxcnt;                             // 최대수량
				$salecnt       = $xml->product[$i]->salecnt;                            // 현재판매량
				$startdate     = $xml->product[$i]->startdate;                          // 판매시작일
				$enddate       = $xml->product[$i]->limitdate;                          // 판매종료일
				$shop_location = $xml->product[$i]->address;                            // 매장위치
				$shop_name     = "";                                                    // 공급업체명
				$shop_addr     = $xml->product[$i]->address;                            // 공급업체주소
				$ckbn = "daoneday";
			}
			else
			{
				$pid           = $xml->product[$i]->pid;                                // 상품코드
				$url           = $xml->product[$i]->url;                                // 상품링크
				$area1         = $xml->product[$i]->area1;                              // 지역1
				$area2         = $xml->product[$i]->area2;                              // 지역2
				$category      = $xml->product[$i]->category;                           // 카테고리명
				$name          = $xml->product[$i]->name;                               // 상품명
				$mimg          = $xml->product[$i]->mimg;                               // 상품이미지
				$caution       = $xml->product[$i]->caution;                            // 사용안내(주의사항)
				$desc          = $xml->product[$i]->desc;                               // sms구문
				$detail        = $xml->product[$i]->detail;                             // 상품상세설명
				$price         = $xml->product[$i]->price;                              // 판매가
				$saleprice     = $xml->product[$i]->saleprice;                          // 할인가
				$salerate      = $xml->product[$i]->salerate;                           // 할인율
				$mincnt        = $xml->product[$i]->mincnt;                             // 최소구매도달인원 
				$maxcnt        = $xml->product[$i]->maxcnt;                             // 최대수량
				$salecnt       = $xml->product[$i]->salecnt;                            // 현재판매량
				$startdate     = $xml->product[$i]->startdate;                          // 판매시작일
				$enddate       = $xml->product[$i]->enddate;                            // 판매종료일
				$shop_location = $xml->product[$i]->shop_location;                      // 매장위치
				$shop_name     = $xml->product[$i]->shop_name;                          // 공급업체명
				$shop_addr     = $xml->product[$i]->shop_addr;                          // 공급업체주소
				$ckbn = "onedaynet";
			}
		}

		//$name = str_replace(array("!","@","#","$","$"), "", $name);   // 특수문자 제거시에 이용

		$pid           = trim($pid);
		$url           = trim($url);
		$area1         = trim($area1);
		$area2         = trim($area2);
		$category      = trim($category);
		$name          = trim($name);
		$mimg          = trim($mimg);
		$caution       = trim($caution);
		$desc          = trim($desc);
		$detail        = trim($detail);
		$price         = trim($price);
		$saleprice     = trim($saleprice);
		$salerate      = trim($salerate);
		$mincnt        = trim($mincnt);
		$maxcnt        = trim($maxcnt);
		$salecnt       = trim($salecnt);
		$startdate     = trim($startdate);
		$enddate       = trim($enddate);
		$shop_location = trim($shop_location);
		$shop_name     = trim($shop_name);
		$shop_addr     = trim($shop_addr);

		$name          = str_replace("'", "`", $name);
		$desc          = str_replace("'", "`", $desc);
		$caution       = addslashes($caution);
		$detail        = addslashes($detail);
		$shop_location = addslashes($shop_location);
		
		//전처리: 가격정보 오류 수정
		if ($price < $saleprice) { echo "Passing because price is smaller than saleprice.<br>"; continue; }
		else if ($price >= $saleprice){
			if ($saleprice && !$salerate){
				$salerate = round(100 - $saleprice/$price*100);
				echo "salerate 0 is now reset to ${salerate}.<br>";
			}
		}
		
		//도메인과 id가 있다면 DB에 넣음
		if ($domain && $pid){
			
			//데이터가 부족한 것은 삭제
			$iChk = $area1.$area2.$category.$_area1.$_area2.$_category;
			
			if(iChk != ''){
				$uData = $domain."_".$pid;
				
				//이미지 경로 처리
				$today = date("Ymd");
				$file = str_replace("/","_",$domain."_".$pid).".jpg";
				$mImgS = $today.'/'.$file;//섬네일경로		
				
				$sql = "select id from coupon where uData = '$uData'";
				$iResult = mysql_query($sql);				
				if(!mysql_fetch_row($iResult)){
					
					if($mimg != ''){
						
					//지역코드추출
					$arrAreaCode = getAreaCode($area1,$shop_addr);
					$area1 = $arrAreaCode[0];
					$area2 = $arrAreaCode[1];
					$area01 = $arrAreaCode[2];
					$area02 = $arrAreaCode[3];
			
					// 지정된 상품 분류 코드로 설정
					//$cat_code = getGoodCode($category,$name)
					if ($category){
						$key = explode("/", $category);
						$num_key = count($key);
						$cat_code = "";
						
						for ($j = 0; $j < $num_key; $j++){
							for ($k = 0; $k < $num_bkbn; $k++){
								if ($key[$j] && mb_strpos("1".$bkbn[$k], $key[$j], 0, "utf-8")){
									$cat_after = $gname[$k]; 
									$cat_code = $code[$k];
									$k = $num_bkbn; $j = $num_key;
								}
							}
						}
					}
					
					$sql = "select NAME1,NAME2 from _area_code where CODE1 like '$area1' and CODE2 like '$area2'";
					$rstArea = mysql_query($sql);
					$arrArea = mysql_fetch_array($rstArea);
					
					$sql = "select name from _meta_site where domain = '$domain'";
					$rstMeta = mysql_query($sql);
					$metaName = mysql_fetch_row($rstMeta);
					
					$sData = $domain."|".$metaName."|".$name."|".$category."|".$shop_name."|".$arrArea['NAME1']."|".$arrArea['NAME2'];


					$sql = "insert into coupon (link,domain, pid, url, area1,   area2, area01,   area02,  category, categoryCode,
						  name, mimg,mImgS, caution,  description, detail, price, saleprice, salerate, mincnt, maxcnt, 
						  salecnt, startdate, enddate, shop_location, shop_name, shop_addr,  ecnt, elog, click, uData,sData) 
					   VALUES ('$rss_addr','$domain', '$pid', '$url', '$area1', '$area2', '$area01', '$area02','$category', '$cat_code',
						 '$name', '$mimg', '$mImgS', '$caution', '$desc', '$detail', '$price', '$saleprice', '$salerate', '$mincnt', '$maxcnt', 
						 '$salecnt', '$startdate', '$enddate', '$shop_location', '$shop_name', '$shop_addr',  '0',     '',      '0','$uData','$sData')";
					
					//섬네일 생성
					cropImg($mimg,300,160,"s",$mImgS);
					}
				}else{
					
					$sql = "update coupon set 
						 link='$rss_addr',shop_location='$shop_location',shop_name='$shop_name',shop_addr='$shop_addr',link='$rss_addr',
						 price = '$price', saleprice = '$saleprice', salerate = '$salerate', startdate = '$startdate',
						 enddate = '$enddate', mincnt = '$mincnt', maxcnt = '$maxcnt', salecnt = '$salecnt'
						 where uData = '$uData'";
				}
		
		
				/*
				$sql = "insert into coupon (link,domain, pid, url, area1,   area2, area01,   area02,  category, categoryCode,
						  name, mimg,mImgS, caution,  description, detail, price, saleprice, salerate, mincnt, maxcnt, 
						  salecnt, startdate, enddate, shop_location, shop_name, shop_addr,  ecnt, elog, click, uData) 
					   VALUES ('$rss_addr','$domain', '$pid', '$url', '$area1', '$area2', '$area01', '$area02','$category', '$cat_code',
						 '$name', '$mimg', '$mImgS', '$caution', '$desc', '$detail', '$price', '$saleprice', '$salerate', '$mincnt', '$maxcnt', 
						 '$salecnt', '$startdate', '$enddate', '$shop_location', '$shop_name', '$shop_addr',  '0',     '',      '0','$uData') 
					   ON DUPLICATE KEY UPDATE							   
						 link='$rss_addr',shop_location='$shop_location',shop_name='$shop_name',shop_addr='$shop_addr',link='$rss_addr',
						 price = '$price', saleprice = '$saleprice', salerate = '$salerate', startdate = '$startdate', mImgS = '$mImgS',
						 enddate = '$enddate', mincnt = '$mincnt', maxcnt = '$maxcnt', salecnt = '$salecnt'";
						 */
			}else{
				$sql = "delete from coupon where uData = '$uData'";
			}
			
			//echo "<hr>".$sql."<hr>\n";
			$iResult = mysql_query($sql);
			
			
		}
		echo $sRecCnt." >> ".$ckbn." >> ".$pid." --- ".$name."<br>";
	}
	
	echo "<br>";

	$Cnt++;
}


$str = explode(" ",microtime());
$end = $str[0]+$str[1];
_($end-$start);

mysql_close($connect);

?>